<template>
  <el-dialog
    title="用户注册"
    :visible.sync="dialogVisible"
    width="600px"
    center
  >
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      label-width="80px"
      :inline="false"
      size="normal"
      label-position="left"
    >
      <!-- 头像 -->
      <el-form-item label="头像" prop="avatar" style="text-align:center">
        <el-upload
          class="avatar-uploader"
          :action="userPost"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :data="objphoto"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <!-- 昵称 -->
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <!-- 图形码 -->
      <el-row>
        <el-col :span="16">
          <el-form-item label="图形码" prop="code">
            <el-input v-model="form.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" style="margin-left:10px"
          ><img :src="mycodeImage" @click="changCodeImage" alt=""
        /></el-col>
      </el-row>
      <!-- 验证码 -->
      <el-row>
        <el-col :span="16">
          <el-form-item label="验证码" prop="rcode">
            <el-input v-model="form.rcode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" style="margin-left:10px"
          ><el-button @click="getRcode" style="width:180px"
            >获取用户验证码</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="rigester">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'Register',
  data () {
    return {
      dialogVisible: false,
      userPost: process.env.VUE_APP_BASEURL + '/uploads',
      mycodeImage: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms',
      imageUrl: '',
      objphoto: {
        image: ''
      },
      form: {
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        rcode: '',
        code: ''
      },
      rules: {
        username: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) return callback(new Error('邮箱啊不能为空'))
              // eslint 开启下一行不检测，因为下面这行的/太多了，eslint不允许
              // eslint-disable-next-line
              const regEmail = /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/
              if (!regEmail.test(value)) {
                return callback(new Error('请输入正确的邮箱地址'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) return callback(new Error('手机哦不能为空'))
              const regPhone = /^1[3-9][0-9]{9}$/
              if (!regPhone.test(value)) {
                return callback(new Error('请输入正确的电话号码'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        code: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) return callback(new Error('图形码不能为空'))
              const regCode = /^\d{4}$/
              if (!regCode.test(value)) {
                return callback(new Error('请输入正确的图形码'))
              }
              //   这个回调一定不能少
              callback()
            },
            trigger: 'blur'
          }
        ],
        rcode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    rigester () {
      this.$refs.form.validate(async valid => {
        if (!valid) return this.$message.error('请填好再提交')
        const registerRes = await this.$axios.post('/register', this.form)
        // console.log(registerRes)
        if (registerRes.code === 200) {
          // 关闭弹框
          this.$message.success('注册成功')
          this.dialogVisible = false
        } else {
          // 失败
          this.$message.error(registerRes.message)

          // 刷新验证码
          this.changCodeImage()
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      //   console.log(res)
      if (res.code === 200) {
        this.form.avatar = res.data.file_path
      } else {
        this.$message.error(res.message)
      }
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,png,gif 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.objphoto.image = file
      return isJPG && isLt2M
    },
    changCodeImage () {
      this.mycodeImage =
        process.env.VUE_APP_BASEURL +
        '/captcha?type=sendsms&t=' +
        (new Date() - 0)
    },
    async getRcode () {
      let count = 0
      this.$refs.form.validateField(['code', 'phone'], errorMessage => {
        if (!errorMessage) {
          count++
        }
      })
      if (count === 2) {
        const res = await this.$axios.post('/sendsms', {
          code: this.form.code,
          phone: this.form.phone
        })
        // console.log(res)
        if (res.code === 200) {
          this.form.rcode = res.data.captcha
        } else {
          this.$message.error(res.message) // 更新验证码
          this.changCodeImage()
        }
      }
    }
  },
  watch: {
    dialogVisible () {
      if (this.dialogVisible === false) {
        this.$refs.form.resetFields()
        this.imageUrl = ''
      }
    }
  }
}
</script>

<style lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
